package com.example.studentmgt.client;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.studentmgt.model.Course;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.net.URISyntaxException;

@Component
public class Client {
    private static final Logger logger = LoggerFactory.getLogger(Client.class);


    @Resource
    private RestTemplate restTemplate;


    public String coursePing() throws Exception {
        URI uri = new URI("http://192.168.254.151:38100/course/ping");
        ResponseEntity<String> exchange = restTemplate.exchange(uri, HttpMethod.GET, null, String.class);
        logger.info(exchange.getBody());
        return exchange.getBody();
    }

    public long createCourse() throws URISyntaxException {
        URI uri = new URI("http://192.168.254.151:30810/course/course");
        ResponseEntity<String> exchange = restTemplate.exchange(uri, HttpMethod.POST, null, String.class);
        if (exchange.getStatusCode().is2xxSuccessful()) {
            JSONObject resBody = JSON.parseObject(exchange.getBody());
            return resBody.getLongValue("id");
        }
        return -1;
    }

    public Course findCourseById(Long id) throws Exception {
        URI uri = new URI("http://192.168.254.151:30810/course/findCourseById?id=" + id);
        ResponseEntity<String> exchange = restTemplate.exchange(uri, HttpMethod.GET, null, String.class);
        logger.info(exchange.getBody());
        if (exchange.getStatusCode().is2xxSuccessful()) {
            Course course = JSON.parseObject(exchange.getBody(), Course.class);
            return course;
        }
        throw new Exception("findCourseById failed:" + id);
    }
}
